package de.mhus.lib.core.lang;

import java.util.HashSet;
import java.util.LinkedList;

import de.mhus.lib.core.MActivator;

public class Base {

	MActivator activator;
	private Base parent;
	private HashSet<String> local;

	public Base(Base parent) {
		this.activator = new ActivatorImpl();
		this.parent = parent;
	}
	
	public Base(MActivator activator) {
		this.activator = activator;
	}
	
	public void destroy() {
		if (activator != null) activator.destroy();
	}

	public boolean isDestroyed() {
		return activator == null || activator.isDestroyed();
	}

	public <T> T base(Class<T> ifc) {
		try {
			if (activator == null) {
				if (parent != null)
					return parent.base(ifc);
				return null;
			}
			
			if (parent != null && !activator.isInstance(ifc) && ( local == null || !local.contains(ifc.getCanonicalName()) ) )
				return parent.base(ifc);
			
			return activator.getObject(ifc);
		} catch (Exception e) {
			e.printStackTrace(); // TODO use logger
		}
		return null;
	}

	public boolean isBase(Class<?> ifc) {
		return activator != null && activator.isInstance(ifc) || parent != null && parent.isBase(ifc);
	}

	public Base getParent() {
		return parent;
	}

	public MActivator getActivator() {
		return activator;
	}

	/**
	 * Define this interface as local handled. The base will not ask the parent base to
	 * lookup this interface.
	 * 
	 * @param ifc
	 */
	public void setLocal(Class<?> ifc) {
		if (local == null) local = new HashSet<String>();
		local.add(ifc.getCanonicalName());
	}
	
}
